package com.oocl.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.SocketException;
import com.oocl.global.GlobalVar;

public class TcpClient {

	public static void main(String[] args) {
		try {
			Socket sk = new Socket("127.0.0.1", 8888);
			while (true) {
				try {
					readFromTcpServerPrint(sk);
					readCommandFromConsoleToTcpServer(sk);
				} catch (SocketException e) {
					// TODO: handle exception
					sk.close();
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void readFromTcpServerPrint(Socket sk) throws IOException {
		InputStream in = sk.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		
		System.out.println(br.readLine());
			while (true) {
				String line = br.readLine();
				if (line.equals("over")) {	
				//	br.close();
					break;
				}
				else {
					System.out.println(line);
				}
			}
	}

	public static void readCommandFromConsoleToTcpServer (Socket sk) throws IOException {
		OutputStream out = sk.getOutputStream();
		BufferedReader rConsole = new BufferedReader(new InputStreamReader(System.in));
		String command = null;
		command = rConsole.readLine();// 读取控制台的输入

		if (command != null) {
			if (command.equals("Q")) {
				out.write((command + "\n").getBytes());// 告诉Server这边客户端已经退出了
				System.out.println("Quit...");
				out.close();
				rConsole.close();
			} else if (command.startsWith("A-P") || command.startsWith("A-D") || command.startsWith("U-P")
					|| command.startsWith("U-D") || command.startsWith("D-P") || command.startsWith("D-D")
					|| command.startsWith("L-PA") || command.startsWith("L-DA") || command.startsWith("L-PD")) {
				boolean isError = checkSyntaxError(command);
				if (isError) {
					System.out.println("Syntax error.Please try again or quit."); // Syntax  error
					out.write(("error\n").getBytes());															
				} else {
					// 如果没有语法错误，则把command发送给server，再由server来解析命令操作
					out.write((command + "\n").getBytes());
				}
			} else { // Invalide command error
				System.out.println("Invalide command.Please try again or quit.");
				out.write(("error\n").getBytes());
			}
		}
	}
	
	// TODO check syntax error
	public static boolean checkSyntaxError(String comm) {
		boolean isError = false;

		return isError;
	}

}
